//
//  PublicMethods.m
//  ElongClient
//
//  Created by Haibo Zhao on 11-8-12.
//  Copyright 2011年 elong. All rights reserved.
//

#import "PublicMethods.h"
#import <mach/mach.h>
#import <mach/mach_host.h>
#import "MBProgressHUD.h"
//自定义加载符


@implementation PublicMethods


+ (void)showAlertTitle:(NSString *)title Message:(NSString *)message {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title 
                                                    message:message
                                                   delegate:nil 
                                          cancelButtonTitle:@"确定"  
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
}


+ (void)showAvailableMemory {
	vm_statistics_data_t vmStats;
    mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
	kern_return_t kernReturn = host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmStats, &infoCount);
	
	if(kernReturn != KERN_SUCCESS) return;
	
	double availableNum = ((vm_page_size * vmStats.free_count) / 1024.0) / 1024.0;
	NSLog(@"<<%.f M can be used>>",availableNum);
}

+(NSInteger) availableMemory{
	vm_statistics_data_t vmStats;
    mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
	kern_return_t kernReturn = host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmStats, &infoCount);
	
	if(kernReturn != KERN_SUCCESS) return 0;
	
	double availableNum = ((vm_page_size * vmStats.free_count) / 1024.0) / 1024.0;
	return round(availableNum);
}


+ (void)closeSesameInView:(UIView *)nowView {
//	ElongClientAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
//	appDelegate.startup.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, 460);
//	[appDelegate.window addSubview:appDelegate.startup.view];
//	appDelegate.startup.contentView = nowView;
//	[appDelegate.startup animtadForClose];
}

+ (NSString *) dateSwitchFromDate:(NSDate *)date{
	NSDate *now = [NSDate date];
	long interval = [now timeIntervalSinceDate:date];
	
	NSInteger minute = round(interval/60);
	NSInteger hour = round(interval/60/60);
	NSInteger day =  round(interval/60/60/24);
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
	[dateFormatter setDateFormat:@"yyyy-MM-dd"];
	if (minute+hour+day==0) {
		return @"刚刚";
	}else if (day>0) {
		NSString *dateStr = [dateFormatter stringFromDate:date];
		[dateFormatter release];
		return dateStr;
	}else if (hour>0) {
		return [NSString stringWithFormat:@"%d小时前",hour];
	}else {
		return [NSString stringWithFormat:@"%d分钟前",minute];
	}
}

+(NSString *)dateSwitchFromDateString:(NSString *)dateString{
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
	[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
	NSDate *date = [dateFormatter dateFromString:dateString];
    if (!date) {
        [dateFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss ZZZ"];
        date = [dateFormatter dateFromString:dateString];
    }
	if (date) {
		return [PublicMethods dateSwitchFromDate:date];
	}
	return dateString;
}
+(NSDate *) nsDateSwithchFromDateString:(NSString *)dateString{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
	[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
	NSDate *date = [dateFormatter dateFromString:dateString];
    if (!date) {
        [dateFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss ZZZ"];
        date = [dateFormatter dateFromString:dateString];
    }
	return date;
}
+(NSString *)dateSwitchFromDateString:(NSString *)dateString dateFormat:(NSString *)dateFormat{
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
	[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
	NSDate *date = [dateFormatter dateFromString:dateString];
    if (!date) {
        [dateFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss ZZZ"];
        date = [dateFormatter dateFromString:dateString];
    }
	if (date) {
        [dateFormatter setDateFormat:dateFormat];
		return [dateFormatter stringFromDate:date];
	}
	return dateString;
}

+(NSString *)flattenHTML:(NSString *)html {  
    
    NSScanner *theScanner;  
    NSString *text = nil;  
    
    theScanner = [NSScanner scannerWithString:html];  
    
    while ([theScanner isAtEnd] == NO) {  
        
        // find start of tag  
        [theScanner scanUpToString:@"<" intoString:NULL] ;   
        
        // find end of tag  
        [theScanner scanUpToString:@">" intoString:&text] ;  
        
        // replace the found tag with a space  
        //(you can filter multi-spaces out later if you wish)  
        NSRange range = [text rangeOfString:@"<" options:NSBackwardsSearch];  
        if (range.location != 0) {  
            text = [text substringFromIndex:range.location];  
        }  
        html = [html stringByReplacingOccurrencesOfString:  
                [ NSString stringWithFormat:@"%@>", text]  
                                               withString:@" "];  
        
    } // while //  
    
    return [html stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
}   


+(UIButton *)buttonWithImage:(UIImage *)image backgroundImage:(UIImage *)bgImag highlightedBackgroundImage:(UIImage *)hbgImage{
	UIImage *stretch = nil;
	UIImage *hstretch = nil;
	if (bgImag) {
		stretch = [bgImag stretchableImageWithLeftCapWidth:bgImag.size.width / 2   topCapHeight:bgImag.size.height / 2];
	}
	if (hbgImage) {
		hstretch = [hbgImage stretchableImageWithLeftCapWidth:hbgImage.size.width / 2   topCapHeight:hbgImage.size.height / 2];
	}
	UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
	[button setExclusiveTouch:YES];
	if (image) {
		[button setImage:image forState:UIControlStateNormal];
	}
	if (bgImag) {
		[button setBackgroundImage:stretch forState:UIControlStateNormal];
	}
	if (hbgImage) {
		[button setBackgroundImage:hstretch forState:UIControlStateHighlighted];
	}
	return button;
}
+(UIImage *)stretchImageNamed:(NSString *)imageName{
	UIImage *stretchImage =  [UIImage noCacheImageNamed:imageName];
	stretchImage = [stretchImage stretchableImageWithLeftCapWidth:stretchImage.size.width/2 topCapHeight:stretchImage.size.height/2];
	return stretchImage;
}
@end


@implementation UIImage (Elong)

+ (UIImage *)noCacheImageNamed:(NSString *)name {
	UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:name ofType:nil]];
	
	return image;
}
+ (UIImage *)stretchableImageWithPath:(NSString *)path {
	UIImage *stretchImg = [UIImage noCacheImageNamed:path];
	return [stretchImg stretchableImageWithLeftCapWidth:stretchImg.size.width / 2
										   topCapHeight:stretchImg.size.height / 2];
}


- (id)compressImageWithSize:(CGSize)size {
	UIGraphicsBeginImageContext(size);
	CGRect imageRect = CGRectMake(0.0, 0.0, size.width, size.height);
	[self drawInRect:imageRect];
	self = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	
	return self;
}


@end


@implementation UIImageView (Elong)

+ (UIImageView *)roundCornerViewWithFrame:(CGRect)rect {
	UIImageView *backView = [[UIImageView alloc] initWithFrame:rect];
	backView.image					= [[UIImage imageNamed:@"white_boder.png"] stretchableImageWithLeftCapWidth:16 topCapHeight:12];
	backView.userInteractionEnabled = YES;
	return [backView autorelease];
}


+ (UIImageView *)graySeparatorWithFrame:(CGRect)rect {
	UIImageView *separatorLine = nil;
	if(rect.size.width>320){
		separatorLine = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"middleLine.png"]];
	}else {
		separatorLine = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"line.png"]];
	}

	separatorLine.contentMode	= UIViewContentModeScaleAspectFill;
	separatorLine.clipsToBounds = YES;
	separatorLine.frame			= rect;
	
	return [separatorLine autorelease];
}


+ (UIImageView *)verticalSeparatorWithFrame:(CGRect)rect {
	UIImageView *graySeparator = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"gray_separator.png"]];
	graySeparator.frame = rect;
	
	return [graySeparator autorelease];
}

@end


@implementation UIView (Public)

#define kTipImageTag  10086
- (void)removeTipMessage {
	UIImageView *backView = (UIImageView *)[self viewWithTag:kTipImageTag];
	if (backView) {
		[backView removeFromSuperview];
	}
}


- (void)showTipMessage:(NSString *)tips {
	UIImageView *backView	= [[UIImageView alloc] initWithFrame:CGRectMake(0, 140, 340, 40)];
	backView.tag			= kTipImageTag;
	
	UILabel *tipLabel			= [[UILabel alloc] initWithFrame:backView.frame];
	tipLabel.backgroundColor	= [UIColor clearColor];
	tipLabel.text				= tips;
	tipLabel.textAlignment		= UITextAlignmentCenter;
	tipLabel.font				= [UIFont boldSystemFontOfSize:16];
	
	[backView addSubview:tipLabel];
	[tipLabel release];
	//backView.center	= CGPointMake(170, 360);
	[self addSubview:backView];
	
	[backView release];
}

- (void)endLoading {
	MBProgressHUD *HUD = (MBProgressHUD *)[self viewWithTag:LOADING_TAG];
	if (HUD) {
		[HUD hide:NO];
	}
	HUD =  (MBProgressHUD *)[self viewWithTag:LOADING_TAG_2];
	if (HUD) {
		[HUD hide:NO];
	}
}


//显示系统Loading
- (void)startLoading {
	MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self];
	[self addSubview:HUD];
	
    // Set determinate mode
    HUD.mode = MBProgressHUDModeDeterminate;
	HUD.removeFromSuperViewOnHide = YES;
	HUD.tag = LOADING_TAG;
    HUD.labelText = @"读取中...";
	[HUD show:YES];
	
	// myProgressTask uses the HUD instance to update progress
    //[HUD showWhileExecuting:@selector(myProgressTask) onTarget:self withObject:nil animated:YES];
}

- (void) startLoading2{
	MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self];
	[self addSubview:HUD];
	
    // Set determinate mode
    HUD.mode = MBProgressHUDModeIndeterminate;
	HUD.removeFromSuperViewOnHide = YES;
	HUD.tag = LOADING_TAG_2;
	[HUD show:YES];
}

- (void)setLoadingProgress:(float)progress {
	MBProgressHUD *HUD = (MBProgressHUD *)[self viewWithTag:LOADING_TAG];
	if (HUD==nil) {
		return;
	}
	if (progress >= 1.0) {
		HUD.progress = 1.0;
		[HUD hide:NO afterDelay:0.2];
	}else if (progress<0.0) {
		progress = 0.0;
	}
	HUD.progress = progress;
}

@end




@implementation NSNumber (Public)

- (NSString *)roundNumberToString {
	int num =  (int)round([self floatValue]);
	return [NSString stringWithFormat:@"%d",num];
}

@end



@implementation UIWebView (Elong)
-(void) setScrollShadowHidden:(BOOL)isHidden{
	id scroller = [self.subviews objectAtIndex:0]; 
	for (UIView *subView in [scroller subviews]){
		if ([[[subView class] description] isEqualToString:@"UIImageView"]) 
			subView.hidden = isHidden;
	}
}
@end